﻿using System.Linq;
using System.Web.Mvc;
using BLL.Security;
using BLL.Services.Authors;
using BLL.Services.Books;
using BLL.Services.Categories;
using BLL.Services.Ratings;
using Web.Infrastructure;
using Web.Models;

namespace Web.Controllers
{
    /// <summary>
    /// The books controller.
    /// </summary>
    public partial class BooksController : FrontendController
    {
        private readonly BLL.Services.Responses.IResponsesService _responsesService;

        private readonly ICategoriesService _categoriesService;

        private readonly IBookService _bookService;

        private readonly IRatingService _ratingService;

        private readonly IAuthorsService _authorsService;

        private readonly IEnvironmentContext _environmentContext;


        public BooksController(IBookService bookService, 
            BLL.Services.Responses.IResponsesService responsesService, 
            ICategoriesService categoriesService, 
            IAuthorsService authorsService, 
            IEnvironmentContext environmentContext,
            IRatingService ratingService)
        {
            _responsesService = responsesService;
            _categoriesService = categoriesService;
            _bookService = bookService;
            _ratingService = ratingService;
            _authorsService = authorsService;
            _environmentContext = environmentContext;
        }

        [HttpGet]
        public virtual ActionResult IndexTemplate()
        {
            return BackBoneView(MVC.Books.Views.Index);
        }

        public virtual ActionResult Index(int? bookId)
        {
            var model = new BookModel();
            if (bookId.HasValue)
            {
                model.Categories = _categoriesService.GetAllCategories.Select(x => new BookModel.CategoryModel(x));
                var book = _bookService.GetBookById(bookId.Value);
                model.CurrentBook = new BookModel.CurrentBookModel(book);
                var user = _environmentContext.User;
                var userId = 0;
                if (user != null)
                {
                    userId = user.UserId;
                }
                var bookRating = _ratingService.GetBookRating(bookId.Value, userId);
                model.CurrentBook.Rating = bookRating.Rating;
                model.CurrentBook.IsCanRate = bookRating.IsCanRate;
                model.CurrentBook.Authors = _authorsService.GetAuthorsByIds(book.AuthorIds).ToArray();
                return BackBoneJson(model);
            }
                model = new BookModel();
                return BackBoneJson(model);
            
        }
    }
}
